import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Switch } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { 
  getAftermentList, 
  batchUpdateStatus, 
  batchDelete,
  addReason,
  updateReason
 } from '@/services/params/api';
import OptForm from './OptForm';
import { MsgType, showMsg } from '@/utils/utils';
import PermissionControl from '@/components/PermissionControl'
import BreadcrumbDept from '@/components/BreadcrumbDept';

const Index: React.FC = () => {
  const actionRef = useRef<ActionType>()
  const [visible, setVisible] = useState<boolean>(false)
  const [currentRow, setCurrentRow] = useState<PARAMSAPI.AftermentItem>({} as PARAMSAPI.AftermentItem)
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([])
  const columns: ProColumns<PARAMSAPI.AftermentItem>[] = [
    {
      title: '类别',
      dataIndex: 'after_type',
      valueType: 'select',
      valueEnum: {
        '': '全部',
        G: '退货',
        R: '退款'
      },
      width: 80
    },
    {
      title: '原因类型',
      dataIndex: 'reason',
      search: false,
      width: 150
    },
    {
      title: '排序',
      dataIndex: 'sort',
      search: false,
      width: 80
    },
    {
      title: '是否可用',
      dataIndex: 'is_use',
      search: false,
      valueType: 'select',
      valueEnum: {
        Y: '是',
        N: '否'
      },
      width: 80,
      render: (_, record) => {
        return <React.Fragment>
          <PermissionControl action_id="800802004">
            <Switch checked={record.is_use === 'Y'} onChange={async () => {
              try {
                await batchUpdateStatus([record.record_id], record.is_use === 'Y' ? 'N' : 'Y', true)
                actionRef.current?.reload()
                showMsg('已保存', MsgType.SUCCESS)
              } catch (error) {
                showMsg(error?.data?.errmsg)
              }
            }}/>
          </PermissionControl>
        </React.Fragment>
      }
    },
    {
      title: '添加时间',
      search: false,
      width: 180,
      render: (dom, entity) => {
        return `${entity.create_date} ${entity.create_time}`
      }
    },
    
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      width: 100,
      render: (_, record) => {
        return [
          <PermissionControl key="edit" action_id="800802005">
            <a onClick={() => {
              setVisible(true);
              setCurrentRow(record);
            }}>编辑</a>
          </PermissionControl>,
          <PermissionControl key="delete" action_id="800802006">
            <a onClick={ async () => {
              try {
                await batchDelete([record.record_id], true)
                showMsg('已删除', MsgType.SUCCESS)
                actionRef.current?.reload()
              } catch (error) {
                showMsg(error?.data?.errmsg)
              }
            }}>删除</a>
          </PermissionControl>
        ]
      }
    }
  ];

  /**
   * 添加，编辑
   * @param values 
   * @returns 
   */
  const handleAdd = async (values: any) => {
    try {
      if (currentRow.record_id) {
        values = Object.assign({}, values, { record_id: currentRow.record_id })
        await updateReason(values)
      } else {
        await addReason(values)
      }
      return true;
    } catch (error) {
     showMsg(error?.data?.errmsg)
     return false 
    }
  }

  return (
    <PageContainer extra={[
     ]} breadcrumb={{}}>
      <ProTable<PARAMSAPI.AftermentItem, COMMON.PageParams & PARAMSAPI.AftermentItem>
        rowKey="record_id"
        bordered
        actionRef={actionRef}
        request={async (params) => {
          try {
            const data: PARAMSAPI.AftermentItemList = await getAftermentList(params)
            return {
              data: data.record_list,
              total: data.sum_record_num
            }
          } catch (error) {
            showMsg(error?.data?.errmsg)
            return {
              data: [],
              total: 0
            }
          }
        }}
        options={false}
        rowSelection={{
          onChange: setSelectedKeys
        }}
        search={{
          span: 6,
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift()
            return [<PermissionControl action_id="800802000">{dom}</PermissionControl>];
          }
        }}
        toolbar={{
          menu: {
            type: 'inline',
            items: [
              {
                key: 'new',
                label: <PermissionControl action_id="800802001">
                    <Button 
                      onClick={() => {
                        setVisible(true);
                        setCurrentRow({} as PARAMSAPI.AftermentItem);
                      }} 
                      type="primary">
                      新增
                    </Button>
                  </PermissionControl>
              },
              {
                key: 'batchban',
                label: <PermissionControl action_id="800802002">
                    <Button 
                      disabled={selectedKeys.length <= 0}
                      onClick={async () => {
                        try {
                          await batchUpdateStatus(selectedKeys as string[], 'N')
                          showMsg('已禁用', MsgType.SUCCESS)
                          actionRef.current?.reload()
                          actionRef.current?.clearSelected?.()
                        } catch (error) {
                          showMsg(error?.data?.errmsg)
                        }
                      }} 
                      type="primary">
                      批量禁用
                    </Button>
                </PermissionControl>
              },
              {
                key: 'batchdelete',
                label: <PermissionControl action_id="800802003">
                    <Button 
                      disabled={selectedKeys.length <= 0}
                      onClick={async () => {
                        try {
                          await batchDelete(selectedKeys as string[])
                          showMsg('已删除', MsgType.SUCCESS)
                          actionRef.current?.reload()
                          actionRef.current?.clearSelected?.()
                        } catch (error) {
                          showMsg(error?.data?.errmsg)
                        }
                      }} 
                      type="primary">
                      批量删除
                    </Button>
                  </PermissionControl>
              }
            ]
          }
        }}
        pagination={{
          showQuickJumper: true
        }}
        columns={columns}
      />

      {
        visible && <OptForm 
          handleVisible={setVisible}
          handleAdd={handleAdd} 
          actionRef={actionRef} 
          record={currentRow}/>
      }
    </PageContainer>
  );
};
export default Index;
